﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;

namespace Ids4Extensions
{
    public static class Ids4SwaggerExtension
    {
        public static IServiceCollection AddSwagger(this IServiceCollection services, OpenApiInfo info, bool useAuthentication = false)
        {
            if (useAuthentication)
            {
                // 配置 IdentityServer4 服务
                services.AddAuthentication("Bearer")
                    .AddJwtBearer("Bearer", options =>
                    {
                        options.Authority = "https://localhost:5001";
                        options.RequireHttpsMetadata = true;
                        options.Audience = "api1";
                    });
            }

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc(info.Version, info);

                if (useAuthentication)
                {
                    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                    {
                        Description = "JWT Authorization header using the Bearer scheme.",
                        Name = "Authorization",
                        In = ParameterLocation.Header,
                        Type = SecuritySchemeType.Http,
                        Scheme = "bearer",
                        BearerFormat = "JWT"
                    });

                    options.AddSecurityRequirement(new OpenApiSecurityRequirement
                    {
                        {
                            new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference  {   Type = ReferenceType.SecurityScheme,  Id = "Bearer"   }
                            },
                            Array.Empty<string>()
                        }
                    });
                }
            });

            // 根据AuthorizeAttributea分配是否需要授权操作
            //if (useOAuth)
            //    c.OperationFilter<SecurityRequirementsOperationFilter>();
            return services;
        }

        public static IApplicationBuilder UseSwagger(this IApplicationBuilder app, string name, bool useAuthentication = false)
        {
            if (useAuthentication)
            {
                // 使用身份验证和 Swagger 中间件
                app.UseAuthentication();
                app.UseAuthorization();
            }

            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", name);
                if (useAuthentication)
                {
                    options.OAuthClientId("mySwaggerClientId");
                    options.OAuthAppName("My Swagger UI");
                    options.OAuthUsePkce();
                }
            });

            return app;
        }

    }
}